package cn.gson.crm.controller.onsales;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.exception.UploadException;
import cn.gson.crm.model.dao.BackDao;
import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.DeliveryDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.MessageDao;
import cn.gson.crm.model.dao.OpportunityDao;
import cn.gson.crm.model.dao.OrderDao;
import cn.gson.crm.model.entity.Attachment;
import cn.gson.crm.model.entity.Back;
import cn.gson.crm.model.entity.Delivery;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Message;
import cn.gson.crm.model.entity.Order;
import cn.gson.crm.model.mapper.OrderMapper;
import cn.gson.crm.service.UploadService;

/**
 * 订单 // 获取订单列表,分页 //未审批订单，分页
 * 
 * @author hzl
 * @date 2018年4月8日
 * @time 下午3:29:30
 */
@Controller
@RequestMapping("crm/order")
public class OrderController {
	@Autowired
	MessageDao messageDao;

	@Autowired
	private UploadService uploadService;

	@Autowired
	OrderDao orderDao;

	@Autowired
	CustomerDao customerDao;

	@Autowired
	EmployeeDao empDao;

	@Autowired
	OpportunityDao oppDao;

	@Autowired
	BackDao backDao;

	@Autowired
	DeliveryDao deliveryDao;
	
	@Autowired
	OrderMapper orderMapper;

	@GetMapping
	public String index() {
		return "onsales/order/orderlist";
	}

	// 添加订单明细表
	@GetMapping("/addorderdetail/{id}")
	public String addorderdetail(HttpServletRequest req, @PathVariable(name = "id") Long id,@RequestParam(name="type",required=false) String type) {
		req.setAttribute("order", orderDao.findOne(id));
		if(type!=null){
			req.setAttribute("type",type);
		}
		return "onsales/order/order_add_detail";
	}

	// 添加回款计划
	@GetMapping("/addReceivable/{id}")
	public String addReceivable(HttpServletRequest req, @PathVariable(name = "id") Long id) {
		Order order = orderDao.findOne(id); 
		req.setAttribute("order", order);
		return "onsales/order/receivable_add";
	}

	// 获取订单列表,分页,根据不同身份
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> getlist(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows, HttpServletRequest req) {
		Employee emp = (Employee) req.getSession().getAttribute("employee");
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));
		Page<Order> order;
		if ("销售员".equals(emp.getRole().getRoleName())) {
			order = orderDao.findByEmployeeAndIsDelete(emp, pr,false);
		} else {
			order = orderDao.findAll(pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", order.getContent());
		data.put("total", order.getTotalElements());
		return data;
	}

	// 未审批订单，分页
	@RequestMapping("audit")
	@ResponseBody
	public Map<String, Object> getauditlist(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows) {
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));
		Page<Order> order = orderDao.findByAuditAndIsDelete("未审核", pr,false);
		Map<String, Object> data = new HashMap<>();
		data.put("rows", order.getContent());
		data.put("total", order.getTotalElements());
		return data;
	}

	/**
	 * 查询所有未删除订单，根据不同身份
	 * 
	 * @author hzl
	 * @return
	 */
	@RequestMapping("orderTopic")
	@ResponseBody
	public JSONArray getOrderTopic(HttpServletRequest req) {
		Employee emp = (Employee) req.getSession().getAttribute("employee");
		JSONArray jsonArray = new JSONArray();

		List<Order> orderlist = new ArrayList<Order>();
		if ("销售员".equals(emp.getRole().getRoleName())) {
			orderlist = orderDao.findByEmployeeAndIsDelete(emp,false);
		} else {
			orderlist = (List<Order>) orderDao.findAll();
		}
		if (orderlist.size() < 1) {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", null);
			jsonObj.put("topic", "没有找到相应的记录！");
			jsonArray.add(jsonObj);
		} else {
			for (Order order : orderlist) {
				jsonArray.add(order);
			}
		}
		return jsonArray;
	}

	/**
	 * 联动，根据所选订单得到相应的金额。
	 */
	@RequestMapping("getMoney")
	@ResponseBody
	public JSONArray getMoney(@RequestParam("orderid") Long oid) {
		JSONArray jsonArray = new JSONArray();
		Order order = orderDao.findOne(oid);
		if (order != null && (order.getOrderMoney() - order.getReceivableMoney()) > 0) {
			for (int i = 1; i <= 10; i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("value", order.getOrderMoney() - order.getReceivableMoney() * 0.1 * i);
				jsonObject.put("money", i * 10 + "%");
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}

	/**
	 * 联动，根据客户查询订单
	 * 
	 * @return
	 */
	@RequestMapping("getOrderByCus")
	@ResponseBody
	public JSONArray getOrderByCus(@RequestParam(value = "customerid", required = false) Long cid,
			HttpSession session) {
		System.out.println("哈哈哈" + cid);
		JSONArray jsonArray = new JSONArray();
		List<Order> orderlist;
		if (cid == null) {
			System.out.println("合理");
			orderlist = orderDao.findByEmployeeAndIsDelete((Employee) session.getAttribute("employee"),false);

		} else {
			orderlist = orderDao.findByCustomerAndIsDelete(customerDao.findOne(cid),false);
			// orderlist= (List<Order>) orderDao.findAll();
		}
		if (orderlist == null) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", null);
			jsonObject.put("topic", "没有查到对应的订单记录！");
			jsonArray.add(jsonObject);
		} else {
			for (Order order : orderlist) {
				jsonArray.add(order);
			}
		}
		return jsonArray;
	}

	/**
	 * 联动，根据客户查询已审核且未发货的订单
	 * 
	 * @return
	 */
	@RequestMapping("getOrderByCusDeAu")
	@ResponseBody
	public JSONArray getOrderByCusDeAu(@RequestParam("customerid") Long cid) {
		JSONArray jsonArray = new JSONArray();
		List<Order> orderlist = orderDao.findByCustomerAndDeliveryAndAuditAndIsDelete(customerDao.findOne(cid), "未发货", "通过",false);
		if (orderlist == null) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", null);
			jsonObject.put("topic", "没有查到对应的订单记录！");
			jsonArray.add(jsonObject);
		} else {
			for (Order order : orderlist) {
				jsonArray.add(order);
			}
		}
		return jsonArray;
	}

	// 添加订单明细表
	@GetMapping("/addorderdetail")
	public String addorderdetail() {
		return "onsales/order/order_add_detail";
	}

	// 保存订单
	@PostMapping("save")
	@ResponseBody
	public JSONObject saveOrder(@Valid Order order, BindingResult br,
			@RequestParam(value = "files", required = false) MultipartFile[] files,
			@RequestParam(value = "provinceName", required = false) String province,
			@RequestParam(value = "cityName", required = false) String city,
			@RequestParam(value = "districtName", required = false) String district,
			@RequestParam(value = "address", required = false) String address,
			@RequestParam(value = "customerid", required = false) Long cid,
			@RequestParam(value = "salesOppid", required = false) Long salesOppid,
			@RequestParam(value = "employeeid", required = false) Long employeeid,
			@RequestParam(value = "auditDate1", required = false) String auditDate,
			@RequestParam(value = "auditEmployeeid", required = false) Long auditEmpid,
			@RequestParam(value = "time1", required = false) String time, HttpServletRequest req) {
		HttpSession session = req.getSession();
		JSONObject result = new JSONObject();
		List<Attachment> attachments =new ArrayList<>();
		if (br.hasErrors()) {
			result.put("err", "校验失败！");
			return result;
		} else {
			if (files != null && files.length > 0) {
				try {
					for (MultipartFile file : files) {
						System.out.println(file.getName());
						Attachment attachment=uploadService.save(file);
						System.out.println(attachment.toString());
						if(attachment!=null){
							attachments.add(attachment);
						}
					}
				} catch (UploadException e){
					result.put("err",e);
					return result;
				}catch (Exception e) {
//					System.out.println("文件上传失败！" + e);
					e.printStackTrace();
					result.put("err", "附件上传失败！");
					return result;
				}
				order.setAttachment(attachments);
			}
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
			Date date = null;
			try {
				System.out.println(time+"时间");
				date = formatter.parse(time);
			} catch (ParseException e) {
				System.out.println(e);
				System.out.println("日期转换异常！");
				result.put("err", "日期转换异常！");
			}catch(Exception e){
				System.out.println(e);
				result.put("err", "保存失败 了！");
			}
			order.setTime(date);
			if (salesOppid == null) {
				order.setSalesOpp(null);
			} else {
				order.setSalesOpp(oppDao.findOne(salesOppid));
			}
			order.setCustomer(customerDao.findOne(cid));
			order.setReceiveAddress(province + city + district + address);
			
			if (order.getId() == null) {// 新增
				Employee employee = (Employee) session.getAttribute("employee");
				order.setNumber("ORDER" + formatter1.format(new Date()) + (10 + (int) (Math.random() * 90))
						+ (char) ('a' + Math.random() * ('z' - 'a' + 1)));
				order.setAudit("未审核");
				order.setState("执行中");
				order.setDelivery("未发货");
				order.setEmployee(employee);
				Order newOrder = orderDao.save(order);
				messageDao.save(new Message("订单", new Date(), null, "新订单", employee.getEmpName()+"添加一条新订单了！"));

				session.setAttribute("newOrder", newOrder);
				result.put("newOrder", newOrder);
			} else {// 编辑
				try {
					if (auditDate == null) {
						order.setAuditDate(null);
					} else {
						order.setAuditDate(formatter.parse(auditDate));
					}
					if (auditEmpid == null) {
						order.setAuditEmployee(null);
					} else {
						order.setAuditEmployee(empDao.findOne(auditEmpid));
					}
					if (employeeid == null) {
						order.setEmployee(null);
					} else {
						order.setEmployee(empDao.findOne(employeeid));
					}
				} catch (ParseException e) {
					System.out.println("审核日期转换异常了！");
					result.put("err", "审核日期转换异常了！");
				} catch (Exception e) {
					e.printStackTrace();
					result.put("err", "保存失败 了1！");
				}
				orderDao.save(order);
			}
		}
		return result;
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public String delete(@PathVariable Long id) {
		Order order =orderDao.findOne(id);
		order.setDelete(true);
		orderDao.save(order);
		return "true";
	}

	// 根据id找出订单
	@GetMapping("find2/{id}")
	@ResponseBody
	public JSONObject getorder(@PathVariable Long id) {
		JSONObject jsonObject = new JSONObject();
		Order order = orderDao.findOne(id);
		jsonObject.put("topic", order.getTopic());
		String tsStr = "";
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			// 方法一
			tsStr = sdf.format(order.getTime());
			// System.out.println(tsStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		jsonObject.put("time1", tsStr);
		jsonObject.put("customerid", order.getCustomer().getId());
		jsonObject.put("customername", order.getCustomer().getName());
		if (order.getSalesOpp() == null) {
			jsonObject.put("oppid", null);
			jsonObject.put("oppname", "没有找到相应的销售机会！");
		} else {
			jsonObject.put("oppid", order.getSalesOpp().getId());
			jsonObject.put("oppname", order.getSalesOpp().getTopic());
		}
		jsonObject.put("orderMoney", order.getOrderMoney());
		jsonObject.put("receivableMoney", order.getReceivableMoney());
		jsonObject.put("note", order.getNote());
		// String address = order.getReceiveAddress();
		jsonObject.put("receiveMan", order.getReceiveMan());
		jsonObject.put("receiveTel", order.getReceiveTel());
		jsonObject.put("address", order.getReceiveAddress());
		return jsonObject;
	}

	@GetMapping("setSequestration/{id}")
	@ResponseBody
	public JSONObject setSequestration(@RequestParam("setSequestration") int setSequestration,
			@PathVariable(name = "id") Long id) {
		JSONObject jsonObject = new JSONObject();
		Order order = orderDao.findOne(id);
		if (setSequestration == 0) {
			order.setSequestration(true);
		} else {
			order.setSequestration(false);
		}
		try {
			orderDao.save(order);
			jsonObject.put("success", "成功！");
		} catch (Exception e) {
			jsonObject.put("err", "失败！");
		}
		return jsonObject;
	}

	// 结束订单
	@GetMapping("finishOrder/{id}")
	@ResponseBody
	public JSONObject finishOrder(@PathVariable(name = "id") Long id) {
		JSONObject jsonObject = new JSONObject();
		Order order = orderDao.findOne(id);
		Boolean s = true;
		if (order.isReturnGoods()) {
			List<Back> backlist = backDao.findByOrder(order);
			for (Back back : backlist) {
				if (!"已完成".equals(back.getState())) {
					jsonObject.put("err", "失败了！还有未完成的退货单。");
					s = false;
					break;
				}
			}
		} else {
			List<Delivery> deliveryList = deliveryDao.findByOrder(order);
			for (Delivery delivery : deliveryList) {
				if (!delivery.getState().equals("已完成")) {
					jsonObject.put("err", "失败了！还有未完成的发货单。");
					s = false;
					break;
				}
			}
		}
		if (s) {
			try {
				orderDao.save(order);
				jsonObject.put("success", "成功！");
			} catch (Exception e) {
				jsonObject.put("err", "失败！");
			}
		}
		return jsonObject;
	}
	
	@PostMapping("selectNumByDay")
	@ResponseBody
	public Integer[] selectNumByDay(){
		Integer[] num=new Integer[7];
		for(int i=0;i<7;i++){
//			num[i]=orderMapper.selectNumByDay(i);
		}
		return num;
	}
 }
